﻿// <copyright file="CategorySortDialog.aspx.cs" company="Auros Ltd.">
//     Copyright (c) Auros Ltd. All rights reserved.
// </copyright>

namespace Auros.Categorisation.Umbraco.Dialogs
{
    using System.Collections.Generic;
    using System.Linq;
    using Auros.Categorisation.Data;
    using umbraco.BasePages;

    /// <summary>
    /// Class defining the Category Sorting Dialog.
    /// </summary>
    public partial class CategorySortDialog : UmbracoEnsuredPage
    {
        /// <summary>
        /// Gets the parent node ID passed to the page through the request object.
        /// </summary>
        /// <returns>The category parent ID.</returns>
        public int GetParentNodeID()
        {
            int parentId = 0;

            if (int.TryParse(this.Request["parentId"], out parentId))
                return parentId;

            return parentId;
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            int parentId = this.GetParentNodeID();

            List<Category> categories = null;

            if (parentId > 0)
                categories = new CategoryRepository().GetCategory(parentId)
                    .Children
                    .OrderBy(c => c.SortOrder)
                    .ToList();
            else
                categories = new CategoryRepository().GetRootCategories()
                    .OrderBy(c => c.SortOrder)
                    .ToList();

            foreach (var category in categories)
            {
                string tableRowFormat = "<tr id=\"{1}\"><td>{0}</td><td>{1}</td></tr>";

                lt_nodes.Text += string.Format(tableRowFormat, category.Name, category.ID);
            }
        }
    }
}